package com.kkd.kkdapp;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;

import android.Manifest.permission;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.os.Build;
import android.text.TextUtils;

import com.kkd.kkdapp.db.app.EADBHelper;
import com.kkd.kkdapp.utils.CrashHandler;
import com.kkd.kkdapp.utils.LogUtil;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.Tencent;
import com.tendcloud.tenddata.TCAgent;
import com.umeng.message.UmengRegistrar;

public class BaseApplication extends Application {

	private static BaseApplication instance;
	public String device_token;
	private List<Activity> mActivitys = new LinkedList<Activity>(); // 所有活着的activity的集合，为了退出app设置的
	private List<Activity> gestureActivitys = new LinkedList<Activity>(); // activity集合

	public IWXAPI api;
	public Tencent mTencent;

	@Override
	public void onCreate() {
		super.onCreate();
		CrashHandler.getInstance().init(getApplicationContext());
		instance = this;
		DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
				.cacheInMemory(true).considerExifParams(true)
				.bitmapConfig(Bitmap.Config.ARGB_8888)
				.imageScaleType(ImageScaleType.IN_SAMPLE_INT).cacheOnDisk(true)
				.build();
		int memClass = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE))
				.getMemoryClass();
		memClass = memClass > 32 ? 32 : memClass;
		// 使用可用内存的1/8作为图片缓存
		final int cacheSize = 1024 * 1024 * memClass / 16;
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				getApplicationContext())
				.defaultDisplayImageOptions(defaultOptions)
				.memoryCacheSize(cacheSize)
				.threadPoolSize(3)
				.threadPriority(Thread.NORM_PRIORITY - 2)
				.memoryCache(new WeakMemoryCache())
				.diskCacheSize(50 * 1024 * 1024)
				.diskCacheFileCount(100)
				// 缓存一百张图片
				.imageDownloader(
						new KkdImageDownloader(getApplicationContext()))
				.build();
		ImageLoader.getInstance().init(config);

		EADBHelper.init(getApplicationContext());

		device_token = UmengRegistrar.getRegistrationId(this);
//		LogUtil.e("TAG", "device_token----->" + device_token);
//		LogUtil.e("TAG", "DeviceInfo----->" + getDeviceInfo(this));
		printChannel();
		// 分享相关
		api = WXAPIFactory.createWXAPI(this, "wx089678a5fca163a4", true);
		api.registerApp("wx089678a5fca163a4");
		mTencent = Tencent.createInstance("1104715459", this);

		// talkingdata
		TCAgent.LOG_ON = true;
		// App ID: 在TalkingData创建应用后，进入数据报表页中，在“系统设置”-“编辑应用”页面里查看App ID。
		// 渠道 ID: 是渠道标识符，可通过不同渠道单独追踪数据。
		TCAgent.init(this, "D79BF9F8160CF111C477368CC29FC63C",
				getTalkingDataId());
		TCAgent.setReportUncaughtExceptions(true);

	}

	public void printChannel() {
		try {
			ApplicationInfo appInfo = this.getPackageManager()
					.getApplicationInfo(getPackageName(),
							PackageManager.GET_META_DATA);
			String channel_on = appInfo.metaData.getString("UMENG_CHANNEL");
			// 测试用的日志，不要删
			System.out.println("------KKD_CHANNEL=" + channel_on
					+ "------------------------------------------------");
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}

	public String getTalkingDataId() {
		String ret = "fuwuduan86";
		try {
			ApplicationInfo appInfo = this.getPackageManager()
					.getApplicationInfo(getPackageName(),
							PackageManager.GET_META_DATA);
			ret = appInfo.metaData.getString("TD_CHANNEL_ID");
			// 测试用的日志，不要删
			System.out.println("------KKD_TalkingData_CHANNEL =" + ret
					+ "------------------------------------------------");
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return ret;
	}

	// 单例模式的方法
	public static BaseApplication getInstance() {
		if (instance == null) {
			instance = new BaseApplication();
		}
		return instance;
	}

	// 添加Activity到容器中
	public void addActivity(Activity activity) {
		if (mActivitys != null && mActivitys.size() > 0) {
			if (!mActivitys.contains(activity)) {
				mActivitys.add(activity);
			}
		} else {
			mActivitys.add(activity);
		}
	}

	public void removeActivity(Activity activity) {
		if (mActivitys != null && mActivitys.size() > 0) {
			mActivitys.remove(activity);
		}
	}

	// 遍历所有Activity并finish，最终推出app
	public void exitKkd() {

		if (mActivitys != null && mActivitys.size() > 0) {
			for (Activity activity : mActivitys) {
				activity.finish();
			}
		}
		System.exit(0);
	}

	// 添加Activity到容器中
	public void addGestureActivity(Activity activity) {
		if (gestureActivitys != null && gestureActivitys.size() > 0) {
			if (!gestureActivitys.contains(activity)) {
				gestureActivitys.add(activity);
			}
		} else {
			gestureActivitys.add(activity);
		}

	}

	// 遍历所有Activity并finish
	public void exitGestureActivity() {

		if (gestureActivitys != null && gestureActivitys.size() > 0) {
			for (Activity activity : gestureActivitys) {
				activity.finish();
			}
		}

	}

	public static boolean checkPermission(Context context, String permission) {
		boolean result = false;
		if (Build.VERSION.SDK_INT >= 23) {
			try {
				Class<?> clazz = Class.forName("android.content.Context");
				Method method = clazz.getMethod("checkSelfPermission",
						String.class);
				int rest = (Integer) method.invoke(context, permission);
				if (rest == PackageManager.PERMISSION_GRANTED) {
					result = true;
				} else {
					result = false;
				}
			} catch (Exception e) {
				result = false;
			}
		} else {
			PackageManager pm = context.getPackageManager();
			if (pm.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
				result = true;
			}
		}
		return result;
	}

	public static String getDeviceInfo(Context context) {
		try {
			org.json.JSONObject json = new org.json.JSONObject();
			android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE);
			String device_id = null;
			if (checkPermission(context, permission.READ_PHONE_STATE)) {
				device_id = tm.getDeviceId();
			}
			String mac = null;
			FileReader fstream = null;
			try {
				fstream = new FileReader("/sys/class/net/wlan0/address");
			} catch (FileNotFoundException e) {
				fstream = new FileReader("/sys/class/net/eth0/address");
			}
			BufferedReader in = null;
			if (fstream != null) {
				try {
					in = new BufferedReader(fstream, 1024);
					mac = in.readLine();
				} catch (IOException e) {
				} finally {
					if (fstream != null) {
						try {
							fstream.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (in != null) {
						try {
							in.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
			json.put("mac", mac);
			if (TextUtils.isEmpty(device_id)) {
				device_id = mac;
			}
			if (TextUtils.isEmpty(device_id)) {
				device_id = android.provider.Settings.Secure.getString(
						context.getContentResolver(),
						android.provider.Settings.Secure.ANDROID_ID);
			}
			json.put("device_id", device_id);
			return json.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
